<template>
	<div class="container-fluid">
		<div class="panel">
			<div class="panel-heading">
				<el-row class="heading-row">
					<el-col :span="24">
						<div class="grid-content bg-purple">
							<el-button type="primary" plain @click="create = true"  icon="el-icon-plus">任务</el-button>
						</div>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<collapse-view content="高级搜索">
							<el-form label-width="50px" label-position="right" :inline="true">
								<el-form-item label="名称">
									<el-input v-model="queryParams.name" placeholder="输入任务名称查询" clearable></el-input>
								</el-form-item>
								<el-form-item label="类型">
									<el-select v-model="queryParams.type" placeholder="选择任务类型查询" clearable>
										<el-option v-for="item in typesSearch" :key="item.value" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="是否必填" label-width="80px">
									<el-switch v-model="queryParams.required" active-color="#13ce66" inactive-value=""></el-switch>
								</el-form-item>
								<el-form-item label="是否上传图片" label-width="100px">
									<el-switch v-model="queryParams.photo" active-color="#13ce66" inactive-value=""></el-switch>
								</el-form-item>
								<el-form-item label="是否有效" label-width="70px">
									<el-switch v-model="queryParams.effective" active-color="#13ce66" inactive-value=""></el-switch>
								</el-form-item>
								<el-form-item>
									<el-button @click="fetchTasks">搜索</el-button>
									<el-button @click="clearSearchForm">清除</el-button>
								</el-form-item>
							</el-form>
						</collapse-view>
					</el-col>
				</el-row>
			</div>
			<div class="panel-body">
				<el-table ref="taskTable" :data="tasks.data" style="width: 100%" v-loading="loading">
					<el-table-column prop="name" label="名称"></el-table-column>
					<el-table-column label="类型" width="80">
						<template slot-scope="scope">
							<span v-html="randerTableType(scope.row)"></span>
						</template>
					</el-table-column>
					<el-table-column label="是否必填" width="100">
						<template slot-scope="scope">
							<span v-html="scope.row.required ? '是' : '否'"></span>
						</template>
					</el-table-column>
					<el-table-column label="是否上传图片" width="120">
						<template slot-scope="scope">
							<span v-html="scope.row.photo ? '是' : '否'"></span>
						</template>
					</el-table-column>
					<el-table-column label="开始时间" width="100">
						<template slot-scope="scope">
							<span v-html="scope.row.start_time ? scope.row.start_time.substr(0, 10) : '未设置'"></span>
						</template>
					</el-table-column>
					<el-table-column label="结束时间" width="100">
						<template slot-scope="scope">
							<span v-html="scope.row.end_time ? scope.row.end_time.substr(0, 10) : '永久生效'"></span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="140">
						<template slot-scope="scope">
							<el-button size="mini" icon="el-icon-edit-outline" @click="handleEdit(scope.$index, scope.row)"></el-button>
							<el-button size="mini" icon="el-icon-close" type="danger" @click="handleDelete(scope.$index, scope.row)" plain></el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="panel-footer text-right">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
											 :current-page="queryParams.page"
											 :page-sizes="[10, 20, 50, 100]"
											 :page-size="queryParams.paginate"
											 layout="total, sizes, prev, pager, next, jumper"
											 :total="tasks.total">
				</el-pagination>
			</div>
		</div>
		<el-dialog title="添加任务信息" :visible.sync="create" width="25%" :before-close="handleClose">
			<el-form :model="createParams" label-width="80px" label-position="right" :rules="createRules" ref="createForm">
				<el-form-item label="任务名称" prop="name">
					<el-input v-model="createParams.name" placeholder="请输入组织名称" clearable></el-input>
				</el-form-item>
				<el-form-item label="任务类型" prop="type">
					<el-select v-model="createParams.type" placeholder="请选择任务类型">
						<el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="createParams.type === 'select'" label="任务参数" prop="params">
					<el-select v-model="createParams.params" multiple filterable allow-create default-first-option placeholder="请定义任务参数" no-data-text="输入参数后按回车创建，可创建多个参数"></el-select>
				</el-form-item>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否必填" prop="required">
							<el-switch v-model="createParams.required" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否拍照" prop="photo" label-width="110px" class="pull-right">
							<el-switch v-model="createParams.photo" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
						</el-form-item>
					</el-col>
				</el-row>
				<collapse-view :expanded="true">
					<el-form-item label="开始时间" prop="start_time">
						<el-date-picker v-model="createParams.start_time" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间"></el-date-picker>
					</el-form-item>
					<el-form-item label="结束时间">
						<el-date-picker v-model="createParams.end_time" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间，留空为永不过期"></el-date-picker>
					</el-form-item>
				</collapse-view>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="create = false">取 消</el-button>
				<el-button type="primary" @click="submitCreateForm('createForm')">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑任务信息" :visible.sync="edit" width="25%" :before-close="handleEditClose">
			<el-form :model="editParams" label-width="80px" label-position="right" :rules="createRules" ref="editForm">
				<el-form-item label="任务名称" prop="name">
					<el-input v-model="editParams.name" placeholder="请输入组织名称" clearable></el-input>
				</el-form-item>
				<el-form-item label="任务类型" prop="type">
					<el-select v-model="editParams.type" placeholder="请选择任务类型">
						<el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="editParams.type === 'select'" label="任务参数" prop="params">
					<el-select v-model="editParams.params" multiple filterable allow-create default-first-option placeholder="请定义任务参数" no-data-text="输入参数后按回车创建，可创建多个参数"></el-select>
				</el-form-item>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否必填" prop="required">
							<el-switch v-model="editParams.required" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否拍照" prop="photo" label-width="110px" class="pull-right">
							<el-switch v-model="editParams.photo" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
						</el-form-item>
					</el-col>
				</el-row>
				<collapse-view :expanded="true">
					<el-form-item label="开始时间" prop="start_time">
						<el-date-picker v-model="editParams.start_time" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间"></el-date-picker>
					</el-form-item>
					<el-form-item label="结束时间">
						<el-date-picker v-model="editParams.end_time" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间，留空为永不过期"></el-date-picker>
					</el-form-item>
				</collapse-view>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleEditClose">取 消</el-button>
				<el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import Vue from 'vue'
	import api from '../apis'

	export default {
		name: "task",
		data () {
			/**
			 * 检测任务参数
			 * @param rule
			 * @param value
			 * @param callback
			 */
			let checkParams = (rule, value, callback) => {
				if (this.createParams.type === "select") {
					if (value.length <= 0) {
						callback(new Error('请至少定义一个任务参数'));
					}
					callback();
				}
			};
			return {
				expanded: true,
				loading: false,
				current: 1,
				create: false,
				edit: false,
				search: '',
				tasks: {
					data: [],
					total: 0
				},
				createParams: {
					name: '',
					type: '',
					required: 1,
					photo: '',
					params: '',
					start_time: '',
					end_time: '',
				},
				editParams: {
					name: '',
					type: '',
					required: '',
					photo: '',
					params: '',
					start_time: '',
					end_time: '',
					defaultTime: [],
				},
				typesSearch: [
					{
						value: '',
						label: '全部'
					},
					{
						value: 'number',
						label: '数量'
					},{
						value: 'branch',
						label: '打分'
					},{
						value: 'text',
						label: '文本'
					},{
						value: 'select',
						label: '选择器'
					},{
						value: 'date',
						label: '日期'
					}
				],
				types: [
					{
						value: 'select',
						label: '选择 —— 用于添加内容选择器'
					},{
						value: 'text',
						label: '文本 —— 用于添加输入文本框'
					},{
						value: 'number',
						label: '数量 —— 用于添加数量输入框'
					},{
						value: 'branch',
						label: '评分 —— 用于添加评分输入框(与数量不同)'
					},{
						value: 'date',
						label: '日期 —— 用于添加日期选择器'
					}
				],
				createRules: {
					name: [
						{ required: true, message: '请输入任务名称', trigger: 'blur' }
					],
					type: [
						{ required: true, message: '请输入任务名称', trigger: 'change' }
					],
					required: [
						{ required: true, message: '请选择是否必填', trigger: 'change' }
					],
					photo: [
						{ required: true, message: '请选择是否上传图片', trigger: 'change' }
					],
					start_time: [
						{ required: true, message: '请选择开始时间', trigger: 'change' }
					],
					params: [
						{ validator: checkParams, trigger: 'change' }
					]
				},
				queryParams: {
					name: '',
					type: '',
					required: '',
					photo: '',
					page: 1,
					paginate: 10,
					effective: ''
				}
			}
		},
		methods: {
			/**
			 * 获取任务数据集合
			 */
			fetchTasks () {
				this.loading = true;
				api.task.fetch(this.queryParams).then(response => {
					this.tasks = response.data;
					this.loading = false;
				});
			},
			/**
			 * 改变任务列表分页大小时触发
			 */
			handleSizeChange (size) {
				this.queryParams.paginate = size;
				this.fetchTasks();
			},
			/**
			 * 改变任务列表页码时触发
			 */
			handleCurrentChange (index) {
				this.queryParams.page = index;
				this.fetchTasks();
			},
			/**
			 * 编辑任务信息
			 */
			handleEdit (index, row) {
				if(row.start_time != null && row.end_time != null){
					let daterange = [];
					daterange[0] = row.start_time;
					daterange[1] = row.end_time;
					row.daterange = daterange;
				}

				this.editParams = {
					...row
				};
				this.edit = true;
				this.editParams.index = index;
			},
			handleDelete (index, row) {
				this.$confirm('此操作将删除任务信息, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					api.task.destroy(row.id).then(() => {
						//遍历分类集合删除指定的ID的分类
						Vue.delete(this.tasks.data, index);
						this.$message.success('删除成功');
						this.fetchTasks();
					}).catch(errors => {
						this.$message.error(errors.response.data.error);
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			/**
			 * 渲染类型
			 */
			randerTableType (row) {
				switch (row.type) {
					case 'number':
						return '数量';
					case 'branch':
						return '打分';
					case 'text':
						return '文本';
					case 'select':
						return '选择器';
					case 'date':
						return '日期';
					default:
						return '未知类型';
				}
			},
			createShop () {
				this.create = true;
			},
			/**
			 * 创建任务
			 */
			submitCreateForm (name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						let params = {
							name: this.createParams.name,
							type: this.createParams.type,
							required: this.createParams.required,
							photo: this.createParams.photo,
							params: JSON.stringify(this.createParams.params),
							start_time: this.createParams.start_time,
							end_time: this.createParams.end_time
						};

						api.task.store(params).then(response => {
							/**
							 * 将响应数据添加到现有数据集合中
							 */
							this.tasks.data.unshift(response.data);
							this.tasks.total += 1;
							this.create = false;
							this.jumpToLastPage();
							this.$refs[name].resetFields();
							this.$message.success('创建成功');
						})
					} else {
						return false;
					}
				});
			},
			/**
			 * 更新任务信息
			 */
			submitEditForm (name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						let params = {
							name: this.editParams.name,
							type: this.editParams.type,
							required: this.editParams.required,
							photo: this.editParams.photo,
							params: this.editParams.params,
							start_time: this.editParams.start_time,
							end_time: this.editParams.end_time
						};

						api.task.update(this.editParams.id, params).then(response => {
							Vue.set(this.tasks.data, this.editParams.index, response.data);
							this.$message.success('更新成功');
							this.handleEditClose();
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						});
					} else {
						return false;
					}
				});
			},
			/**
			 * 跳转到最后一页
			 */
			jumpToLastPage () {
				let last = Math.ceil(this.tasks.total / this.queryParams.paginate);
				if (this.queryParams.page < last) {
					this.queryParams.page = last;
				}
			},
			/**
			 * 关闭表单
			 */
			handleClose () {
				this.create = false;
				this.$refs['createForm'].resetFields();
			},

			/**
			 * 关闭编辑表单
			 */
			handleEditClose () {
				this.edit = false;
				this.$refs['editForm'].resetFields();
			},
			/**
			 * 清除表单内容
			 */
			clearSearchForm () {
				this.queryParams.name = '';
				this.queryParams.type = '';
				this.queryParams.required = '';
				this.queryParams.photo = '';
				this.fetchTasks();
			}
		},
		mounted () {
			/**
			 * 获取任务数据集合
			 */
			this.fetchTasks();
		}
	}
</script>

<style lang="scss">
	.el-select,.el-select--small {
		width: 100%;
	}
	.el-date-editor.el-input, .el-date-editor.el-input__inner {
		width: 100%;
	}
</style>
